<template>
  <div class="login-container">
    <!-- 登录卡片 -->
    <a-card class="login-card" :bordered="false">
      <template #title>
        <div class="card-title">
          <img src="/icon/logo.svg" alt="AI Logo" class="logo" />
          <h1>途杰 AI</h1>
        </div>
      </template>

      <!-- 注册/登录切换标签 -->
      <div class="mode-toggle">
        <a-radio-group v-model:value="isRegister" button-style="solid">
          <a-radio-button :value="false">登录</a-radio-button>
          <a-radio-button :value="true">注册</a-radio-button>
        </a-radio-group>
      </div>

      <!-- 登录/注册表单 -->
      <a-form ref="formRef" :model="form" layout="vertical" @finish="handleFinish">
        <!-- 账号 -->
        <a-form-item name="account" :rules="[{ validator: validateAccount, trigger: 'blur' }]">
          <a-input
            v-model:value="form.account"
            :placeholder="isRegister ? '请输入账号' : '请输入账号（默认为手机号/邮箱）'"
            size="large"
            allow-clear
          >
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>

        <!-- 密码 -->
        <a-form-item
          name="password"
          :rules="[
            { required: true, message: '请输入密码' },
            { min: 6, message: '密码至少6位' }
          ]"
        >
          <a-input-password
            v-model:value="form.password"
            placeholder="请输入密码（默认为手机号/邮箱）"
            size="large"
          >
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
        </a-form-item>

        <!-- 注册专属字段 -->
        <template v-if="isRegister">
          <!-- 确认密码 -->
          <a-form-item
            name="confirmPassword"
            :rules="[
              { required: true, message: '请确认密码' },
              { validator: validateConfirmPassword, trigger: 'blur' }
            ]"
          >
            <a-input-password
              v-model:value="form.confirmPassword"
              placeholder="请确认密码"
              size="large"
            >
              <template #prefix>
                <LockOutlined />
              </template>
            </a-input-password>
          </a-form-item>

          <!-- 邮箱（用于找回密码） -->
          <a-form-item
            name="email"
            :rules="[{ required: false }, { validator: validateEmail, trigger: 'blur' }]"
          >
            <a-input
              v-model:value="form.email"
              placeholder="选填：绑定邮箱（用于找回密码）"
              size="large"
            >
              <template #prefix>
                <MailOutlined />
              </template>
            </a-input>
          </a-form-item>
        </template>

        <!-- 登录按钮 -->
        <a-form-item>
          <a-button type="primary" html-type="submit" size="large" block :loading="loading">
            {{ isRegister ? '立即注册' : '登录' }}
          </a-button>
        </a-form-item>
      </a-form>

      <!-- 忘记密码 -->
      <div v-if="!isRegister" class="toggle-mode">
        <a @click="showModal = true">忘记密码？</a>
      </div>

      <!-- 第三方登录 -->
      <div class="social-login" v-if="!isRegister">
        <div class="divider">
          <span>第三方账号登录</span>
        </div>
        <div class="social-icons">
          <a-tooltip title="微信登录">
            <WechatOutlined class="icon wechat" />
          </a-tooltip>
          <a-tooltip title="QQ登录">
            <QqOutlined class="icon qq" />
          </a-tooltip>
          <a-tooltip title="GitHub登录">
            <GithubOutlined class="icon github" />
          </a-tooltip>
        </div>
      </div>
    </a-card>

    <!-- 使用模态框组件 -->
    <ChangePasswordModal v-model="showModal" @submit="onPasswordChangeSubmit" />
  </div>
</template>

<script setup>
import Http from '@/api/http'
import router from '@/router'
import { isLogin, useUserStore } from '@/stores/user'
import {
  GithubOutlined,
  LockOutlined,
  MailOutlined,
  PhoneOutlined,
  QqOutlined,
  UserOutlined,
  WechatOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { onMounted, reactive, ref } from 'vue'
import ChangePasswordModal from '@/views/component/modify-password.vue'

// 表单引用
const formRef = ref()
const showModal = ref(false)
// 处理密码修改提交成功
const onPasswordChangeSubmit = (formData) => {
}
// 是否注册模式
const isRegister = ref(false)
// 表单数据
const form = reactive({
  account: '',
  password: '',
  confirmPassword: '',
  email: ''
})

// 状态
const loading = ref(false)

// 校验账号
const validateAccount = (rule, value) => {
  if (!value) return Promise.reject('请输入账号')
  return Promise.resolve()
}

// 校验邮箱
const validateEmail = (rule, value) => {
  if (!value) return Promise.resolve()
  const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  if (!emailPattern.test(value)) {
    return Promise.reject('邮箱格式不正确')
  }
  return Promise.resolve()
}

// 校验确认密码
const validateConfirmPassword = (rule, value) => {
  if (value !== form.password) {
    return Promise.reject('两次密码输入不一致')
  }
  return Promise.resolve()
}

// 表单提交
const handleFinish = () => {
  formRef.value
    .validateFields()
    .then(() => {
      loading.value = true
      const api = isRegister.value ? '/auth/register' : '/auth/login'
      const data = { ...form }
      if (!isRegister.value) {
        delete data.confirmPassword
        delete data.email
      }

      Http.post(api, data)
        .then((res) => {
          if (res.code !== 200 || !res.data) {
            return
          }

          if (isRegister.value) {
            message.success('注册成功，欢迎使用途杰AI！')
            isRegister.value = false // 切换到登录
            form.confirmPassword = ''
            form.email = ''
            const { token } = res.data
            const userStore = useUserStore()
            userStore.token = token
            router.push('/')
          } else {
            const { token } = res.data
            const userStore = useUserStore()
            userStore.token = token
            message.success('登录成功，欢迎使用途杰AI！')
            router.push('/')
          }
        })
        .catch((err) => {
          message.error(err.message || '请求失败')
        })
        .finally(() => {
          loading.value = false
        })
    })
    .catch((errorInfo) => {
    })
}

onMounted(() => {
  if (isLogin()) {
    router.push('/')
  }
})
</script>

<style scoped>
.login-container {
  position: relative;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url(/login-bg.jpg);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  overflow: hidden;
}

.login-card {
  position: relative;
  z-index: 1;
  width: 400px;
  max-width: 90%;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  background: rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
  transform: translateY(0);
  transition: transform 0.3s ease;
}

.card-title {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 24px;
}

.logo {
  width: 40px;
  margin-top: 12px;
  filter: drop-shadow(0 0 10px rgba(255, 255, 255, 0.5));
}

.card-title h1 {
  color: #fff;
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.mode-toggle {
  padding: 0 20px 10px;
  text-align: center;
}

:deep(.ant-radio-button-wrapper) {
  background: transparent;
  color: #fff;
  border-color: rgba(255, 255, 255, 0.3);
}

:deep(.ant-radio-button-wrapper-checked) {
  background: rgba(255, 255, 255, 0.2);
  border-color: #fff;
  color: #fff;
}

:deep(.ant-form) {
  padding: 0 20px;
}

:deep(.ant-input-affix-wrapper),
:deep(.ant-input) {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: #fff;
}

:deep(.ant-input::placeholder) {
  color: rgba(255, 255, 255, 0.6);
}

:deep(.ant-input-affix-wrapper:hover),
:deep(.ant-input-affix-wrapper-focused) {
  border-color: #fff;
  box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.2);
}

:deep(.ant-input-prefix) {
  color: rgba(255, 255, 255, 0.6);
}

:deep(.ant-btn-primary) {
  background: linear-gradient(45deg, #4facfe 0%, #00f2fe 100%);
  border: none;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  box-shadow: 0 4px 15px rgba(79, 172, 254, 0.4);
}

.toggle-mode {
  text-align: center;
  margin: 16px 0;
  color: rgba(255, 255, 255, 0.8);
}

.toggle-mode a {
  color: #fff;
  font-weight: 500;
  text-decoration: none;
}

.toggle-mode a:hover {
  text-decoration: underline;
}

.social-login {
  padding: 20px;
  text-align: center;
}

.divider {
  position: relative;
  height: 1px;
  background: rgba(255, 255, 255, 0.2);
  margin: 24px 0;
}

.divider span {
  position: absolute;
  top: -10px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(255, 255, 255, 0.15);
  padding: 0 15px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.social-icons {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.icon {
  font-size: 24px;
  cursor: pointer;
  transition: all 0.3s;
}

.icon.wechat {
  color: #07c160;
}

.icon.qq {
  color: #12b7f5;
}

.icon.github {
  color: #fff;
}

.icon:hover {
  transform: scale(1.2);
}

@media (max-width: 480px) {
  .login-card {
    width: 90%;
    margin: 20px;
  }

  .card-title h1 {
    font-size: 20px;
  }
}
</style>
